package com.yjd.msg.comm.core.service.impl;

import com.alibaba.fastjson.JSON;

import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServiceHolder;
import com.yjd.comm.util.SpringContextHolder;
import com.yjd.msg.comm.core.model.MnsMessage;
import com.yjd.msg.comm.core.service.IMnsDisposeService;
import com.yjd.msg.comm.enums.MsgOrderServiceEnum;
import com.yjd.msg.comm.enums.MsgStatusEnum;
import com.yjd.msg.comm.enums.MsgTypeEnum;
import com.yjd.msg.comm.model.MsgDisposeModel;
import com.yjd.msg.comm.model.MsgInfoModel;
import com.yjd.msg.comm.model.MsgOrderModel;
import com.yjd.msg.comm.service.IMsgDisposeService;
import com.yjd.msg.comm.service.IMsgInfoService;
import com.yjd.msg.comm.service.IMsgOrderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by yjd-wap on 2018/1/22.
 */
public class MnsDisposeServiceImpl extends BaseServiceImpl implements IMnsDisposeService {

    @Resource
    private IMsgOrderService msgOrderService;

    @Resource
    private IMsgInfoService msgInfoService;

    @Resource
    private IMsgDisposeService msgDisposeService;

    private static Logger logger = Logger.getLogger(MnsDisposeServiceImpl.class);
    @Override
    public MnsMessage create(String ref_id, MsgTypeEnum msgTypeEnum, MsgOrderServiceEnum msgOrderServiceEnum, String message) throws Exception {
        if (StringUtils.isBlank(ref_id) || msgTypeEnum == null|| StringUtils.isBlank(message)||msgOrderServiceEnum==null) {
            FrameUtil.throwBaseException1("参数异常");
        }
        long currentTime = FrameUtil.getTime();
        // 持久化消息
        MsgOrderModel msgOrderModel = new MsgOrderModel();
        msgOrderModel.setCreate_time(currentTime);
        if ((msgOrderModel = msgOrderService.insert(msgOrderModel)) == null) {
            FrameUtil.throwBaseException1("生产消息异常");
        }
        // 消息存到msg库
        MsgInfoModel msgInfoModel = new MsgInfoModel();
        msgInfoModel.setRef_id(ref_id);
        msgInfoModel.setMsg_order_id(msgOrderModel.getId());
        msgInfoModel.setMsg_type(msgTypeEnum.getCode());
        msgInfoModel.setStatus(MsgStatusEnum.PENDING.getCode());
        msgInfoModel.setContent(message);
        msgInfoModel.setMsg_source(msgOrderServiceEnum.getCode());
        msgInfoModel.setFail_count(0);
        msgInfoModel.setMax_fail(10);
        msgInfoModel.setCreate_time(currentTime);
        msgInfoModel.setUpdate_time(currentTime);
        msgInfoModel.setNext_time(FrameUtil.getTime(DateUtils.addMinutes(new Date(), 2)));
        if ((msgInfoModel = msgInfoService.insert(msgInfoModel)) == null|| msgInfoModel.getMsg_id() == null) {
            FrameUtil.throwBaseException1("插入消息异常");
        }
        return new MnsMessage(msgInfoModel.getMsg_id(),msgOrderModel.getId(),msgTypeEnum,message,MsgStatusEnum.PENDING.getCode(),
                "msgOrderService",ref_id);
    }

    @Override
    public boolean verify(Long msgId,String orderServiceName) throws Exception {
        MsgInfoModel msgInfoModel = null;
        if (msgId == null || (msgInfoModel = msgInfoService.getModelById(msgId, DbWREnums.READ)) == null) {
            logger.error("发送消息验证失败消息id," +msgId);
            return false;
        }
        // 远程调用消息发起应用的订单是否存在
        IMsgOrderService verifyOrderService = ServiceHolder.getLocalService(IMsgOrderService.class,orderServiceName);
        MsgOrderModel orderModel = verifyOrderService.getModelById(msgInfoModel.getMsg_order_id(),DbWREnums.WRITE);
        if(orderModel==null){
            logger.error("消息源订单记录不存在，消息体："+ JSON.toJSONString(orderModel));
            return false;
        }
        return true;
    }

    @Override
    public boolean isFinished(MnsMessage message) throws Exception {
        if (message == null || message.getMsg_id() == null
                || message.getMsgTypeEnum() == null
                || StringUtils.isBlank(message.getCustomer_name())) {
            FrameUtil.throwBaseException1("参数异常");
        }
        // 消息是否存在
        MsgInfoModel msgInfoModel = msgInfoService.getModelById(message.getMsg_id(),DbWREnums.READ);
        // 消息不存在或消息状态不等于失败或者待处理，则不处理消息
        if (msgInfoModel == null|| MsgStatusEnum.CONSUME_SUCCESS.getCode() == msgInfoModel.getStatus().intValue()) {
            return true;
        }
        return false;
    }

    @Override
    public void finished(MnsMessage message) throws Exception {
        if (message == null || message.getMsg_id() == null||StringUtils.isBlank(message.getCustomer_name())) {
            FrameUtil.throwBaseException1("参数异常");
        }
        MsgDisposeModel msgDisposeModel = new MsgDisposeModel();
        msgDisposeModel.setCustomer_name(message.getCustomer_name());
        msgDisposeModel.setRef_id(message.getMsg_id()+"");
        msgDisposeModel.setCreate_time(FrameUtil.getTime());
        msgDisposeService.insert(msgDisposeModel);
    }

    @Override
    public IBaseDao getBaseDao() {
        return null;
    }
}
